package com.vv.tools.common.util;

import com.fasterxml.jackson.core.type.TypeReference;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * 本地缓存 data/cache.json
 * 存储结构 Map<String, String>
 *
 * @author wen.li
 */
@Slf4j
public class CacheUtil {

    private static final String FILE_PATH = "classpath:data/cache.json";

    private static final Map<String, String> MAP = new ConcurrentHashMap<>();

    private static final AtomicBoolean UPDATE_FLAG = new AtomicBoolean(false);

    private static final ScheduledExecutorService SCHEDULED_EXECUTOR = Executors.newScheduledThreadPool(1);

    static {
        initDate();
        SCHEDULED_EXECUTOR.scheduleAtFixedRate(CacheUtil::saveDate, 60, 60, TimeUnit.SECONDS);
    }

    private CacheUtil() {
    }

    public static String get(String key) {
        return MAP.get(key);
    }

    public static void put(String key, String value) {
        UPDATE_FLAG.set(true);
        MAP.put(key, value);
    }

    private static void initDate() {
        if (MapUtils.isEmpty(MAP)) {
            String s = FileUtils.read(Objects.requireNonNull(FileUtils.getClassPathFile(FILE_PATH)));
            if (StringUtils.isNotBlank(s)) {
                MAP.putAll(Objects.requireNonNull(JsonUtil.toObject(s, new TypeReference<>() {

                })));
            }
        }
    }

    private static void saveDate() {
        if (UPDATE_FLAG.get()) {
            FileUtils.write(Objects.requireNonNull(FileUtils.getClassPathFile(FILE_PATH)), JsonUtil.toJsonString(MAP));
            UPDATE_FLAG.set(false);
        }
    }

    public static boolean containsKey(String data) {
        return MAP.containsKey(data);
    }

}
